from django.shortcuts import render
from django.http import HttpResponseForbidden
from .models import News, Banner, Comment, HotNews
import logging
from django.db.models import F, Q
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from utils.response_code import ResultResponse, Code
import json
from haystack.views import SearchView


logger = logging.getLogger("django")


def get_news_list(request):
    try:
        tag_id = int(request.GET.get("tag_id", 0))
    except Exception as e:
        logger.error("分类错误{}".format(e))
        tag_id = 0
    try:
        page = int(request.GET.get("page", 1))
    except Exception as e:
        logger.error("页面错误{}".format(e))
        page = 1

    news_list = News.objects.values("title", "digest", "image_url", "update_time", "id").annotate(tag__name=
                                                                                                  F("tag__name"),
                                                                                                  author=
                                                                                                  F('author__username'))
    news_info = news_list.filter(is_delete=False, tag_id=tag_id) or news_list.filter(is_delete=False)

    pages = Paginator(news_info, 5)
    try:
        news = pages.page(page)
    except Exception as e:
        logger.error("分页数据不存在{}".format(e))
        news = pages.page(pages.num_pages)

    total_page = pages.num_pages

    data = {
        "news": list(news),
        "total_page": total_page,
    }

    return ResultResponse(data=data)


def get_news_detail(request, news_id):
    print(news_id)
    news = News.objects.select_related("author", "tag").only("title", "update_time", "content", "author__username",
                                                             "tag__name").filter(is_delete=False, id=news_id).first()
    comments = Comment.objects.select_related("author").only("author__username", "update_time", "content",
                                                             "parent__update_time").\
        filter(is_delete=False, news_id=news_id)

    comments_list = []
    for comment in comments:
        comments_list.append(comment)

    if news:
        News.increase_click(news)
        print(news)
        print(locals())
        return render(request, "news/news_detail.html", locals())

    else:
        return HttpResponseForbidden("Page Not Found")


def get_banner(request):
    banner = Banner.objects.only('image_url', 'news__title').select_related('news').filter(is_delete=False)\
        .order_by('priority')
    print(banner)
    banner_info = []
    for i in banner:
        banner_info.append({
            "image_url": i.image_url,
            "news_title": i.news.title,
            "news_id": i.news.id,
        })
    data = {
        "banner": banner_info
    }
    print(data)
    return ResultResponse(data=data)


def get_comment(request, news_id):
    if request.method == "POST":
        if not request.user.is_authenticated:
            return ResultResponse(errno=Code.ERRVERIFY, errmsg="用户没有登陆")

        if not News.objects.only("id").filter(is_delete=False, id=news_id).exists():
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

        json_data = request.body

        if not json_data:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

        print(json_data)

        dict_data = json.loads(json_data)

        content = dict_data.get("content")

        if not content:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="评论的内容不能为空")

        parent_id = dict_data.get('parent_id')
        if parent_id:
            if not  Comment.objects.only("id").filter(is_delete=False, id=parent_id, news_id=news_id).exists():
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="评论的内容不能为空")
            news_content = Comment()
            news_content.content = content
            news_content.news_id = news_id
            news_content.author = request.user
            news_content.parent_id = parent_id if parent_id else None
            news_content.save()
            data = {
                "author": news_content.author.username,
                "content": news_content.content,
                "update_time": news_content.update_time,
                "content_id": news_content.id,
                "news_id": news_content.news_id,
                "parent": {
                    "author": news_content.parent.author.username,
                    "update_time": news_content.parent.update_time,
                }
            }
        else:
            news_content = Comment()
            news_content.content = content
            news_content.news_id = news_id
            news_content.author = request.user
            news_content.parent_id = parent_id if parent_id else None
            news_content.save()
            data = {
                "author": news_content.author.username,
                "content": news_content.content,
                "news_id": news_content.news_id,
                "update_time": news_content.update_time,
                "content_id": news_content.id,
            }
        return ResultResponse(data=data)
    else:
        pass


# 搜索
class Search(SearchView):

    template = "news/search.html"

    def create_response(self):
        # 接收前台用户输入的值
        # kw='python'
        # 参数为page和q是默认的
        query = self.request.GET.get('q', '')
        if not query:
            show = True
            hot_news = HotNews.objects.select_related('news').only("news_id", "news__title", "news__image_url").\
                filter(is_delete=False).order_by("priority")
            count = hot_news.count()
            paginator = Paginator(hot_news, 5)
            try:
                page = paginator.get_page(int(self.request.GET.get("page", 1)))
            except PageNotAnInteger:
                page = paginator.get_page(1)
            except EmptyPage:
                page = paginator.page(paginator.num_pages)
            return render(self.request, "news/search.html", locals())
        else:
            show = False
            return super().create_response()
